#include <iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include "com.hpp"
#include <sys/shm.h>


int defaultid = -1;
int Mode = 0666;
int gsize = 4096;
const int projid = 0x66;

class shm
{
private:
    
    void CreateHelper(int flag)
    {
        shmget(_shmid, _size, flag);
    }

    void Create()
    {
        CreateHelper(IPC_CREAT | IPC_EXCL | Mode);
    }

    void Get()
    {
        CreateHelper(IPC_CREAT);
    }

    void Attach()
    {
        _start_mem = shmat(_shmid,nullptr,0);
        if((long long)_start_mem < 0)
            ERR_EXIT("shmat");
    }
    void DeAttach()
    {
        shmdt(_start_mem);
    }

    void Destroy()
    {
        DeAttach();
        if(_user == "Create")
        {
            int n = shmctl(_shmid,IPC_RMID,nullptr);
            if(n < 0)
                ERR_EXIT("shmctl");
        }
    }

public:
    shm(const std::string & pathname, int projid, const std::string & usertype)
    : _shmid(defaultid)
    , _size(gsize)
    , _start_mem(nullptr)
    , _user(usertype)
    {
        int _key = ftok(pathname.c_str(), projid);
        if(_key < 0)
        {
            ERR_EXIT("ftok");
        }
        if(_user == "Create")
            Create();
        else if(_user == "User")
            Get();
        else
        {}
        Attach();
    }

    ~shm()
    {
        if(_user == "Create")
        {
            Destroy();
        }
    }
private:
    int _shmid;
    key_t _key;
    int _size;
    void* _start_mem;
    std::string _user;
};